package cn.school.web;

import cn.school.entity.Grade;
import cn.school.service.GradeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "GradeJsonServlet",value ="/gradeJsonServlet" )
public class GradeJsonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    GradeService gradeService=new GradeService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Grade> all = gradeService.findALL();
        //输出一个json格式的文本
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for(int i=0;i<all.size();i++){
            Grade g=all.get(i);
            sb.append("{");
            sb.append("\"id\":"+g.getId());
            sb.append(",\"gname\":\""+g.getGname()+"\"");
            sb.append("}");
            if(i<all.size()-1)
                sb.append(",");
        }
        sb.append("]");
        System.out.println(">>>>>>>>>>>>>>>"+sb);
        //响应的格式是json
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(sb);
        writer.flush();
    }
}
